package ar.com.sebasoft.rembrandt;

import java.io.File;
import java.text.DateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.BaseColumns;
import android.provider.MediaStore;
import android.provider.MediaStore.Images.ImageColumns;
import android.provider.MediaStore.MediaColumns;
import android.support.v4.app.FragmentStatePagerAdapter;
import android.support.v4.content.CursorLoader;
import android.support.v4.content.Loader;
import android.support.v4.content.Loader.OnLoadCompleteListener;
import android.support.v4.view.ViewPager;
import android.util.Log;
import ar.com.sebasoft.rembrandt.adapter.WebViewPagerAdapter;
import ar.com.sebasoft.rembrandt.fragment.FullscreenArrayFragment;
import ar.com.sebasoft.rembrandt.model.Foto;
import ar.com.sebasoft.rembrandt.util.SystemHelper;
import ar.com.sebasoft.rembrandt.util.SystemUiHider;

import com.actionbarsherlock.app.SherlockFragmentActivity;
import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuItem;
import com.actionbarsherlock.view.Window;
import com.androidquery.AQuery;

/**
 * An example full-screen activity that shows and hides the system UI (i.e.
 * status bar and navigation/system bar) with user interaction.
 * 
 * @see SystemUiHider
 */
public class PresentationActivity extends SherlockFragmentActivity implements OnLoadCompleteListener<Cursor> {
	public static final String PARAM_PHOTO = "rembrandt.photo";
	public static final String PARAM_TITLE = "rembrandt.title";
	public static final String PARAM_DATE = "rembrandt.date";
	public static final String PARAM_PATH = "rembrandt.title";
	public static final String PARAM_GALLERY = "rembrandt.gallery";
	public static final String PARAM_PHOTO_ID = "rembrandt.photo_id";
	private static final String JOKER_STRING = "%";
	private static final Object EMPTY_STRING = "";

	FragmentStatePagerAdapter pagerAdapter = null;

	private Intent mShareIntent;
	private ViewPager viewPager;
	private List<Foto> mLista = null;
	private int sortOrder;
	private boolean sortOrient;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		this.requestWindowFeature(Window.FEATURE_PROGRESS);

		this.setContentView(R.layout.activity_presentation);

		SystemHelper.setCurrentContext(this.getApplicationContext());

		// Show the Up button in the action bar.
		this.getSupportActionBar().setDisplayHomeAsUpEnabled(true);
		Bundle bundle = this.getIntent().getExtras();

		this.setupList(bundle);

		this.setupPager(bundle);

		if ((this.mLista != null) && !this.mLista.isEmpty()) {
			this.setupShare(this.mLista.get(0));
		}
		this.setProgressBarIndeterminate(false);
		this.setProgressBarVisibility(true);
	}

	private void setupList(Bundle bundle) {
		if (bundle.containsKey(PARAM_PHOTO)) {
			String path = bundle.getString(PARAM_PHOTO);
			String title = null;
			long imgID = bundle.getLong(PARAM_PHOTO_ID, -1);
			long fecha = bundle.getLong(PARAM_DATE, -1);
			if (bundle.containsKey(PARAM_TITLE)) {
				title = bundle.getString(PARAM_TITLE);
			}
			if (this.mLista == null) {
				this.mLista = new ArrayList<Foto>();
			}
			this.mLista.add(new Foto(imgID, path, title, (fecha > 0) ? new Date(fecha) : null));
		}
		if (bundle.containsKey(PARAM_GALLERY)) {
			ArrayList<String> lista = bundle.getStringArrayList(PARAM_GALLERY);
			if (!lista.isEmpty()) {
				if (this.mLista == null) {
					this.mLista = new ArrayList<Foto>();
				}
				for (String sFoto : lista) {
					this.mLista.add(Foto.fromString(sFoto));
				}
			}
		}
		if (bundle.containsKey(PARAM_PATH)) {
			this.cargarFotos(bundle.getString(PARAM_PATH));
		}
	}

	private void cargarFotos(String path) {
		if (path != null) {
			Log.d(SystemHelper.APP_TAG, "CARGANDO PATH=" + path);
			// Donde se almacenan las imagenes
			Uri uriExt = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
			Uri uriInt = MediaStore.Images.Media.INTERNAL_CONTENT_URI;
			// Las columnas que queremos
			String[] projection = { BaseColumns._ID, MediaColumns.DATA, ImageColumns.DATE_TAKEN, MediaColumns.DATE_ADDED, MediaColumns.TITLE, MediaColumns.DISPLAY_NAME, ImageColumns.DESCRIPTION };
			// Solo queremos las miniaturas
			String selection = MediaColumns.DATA + " LIKE ?";
			String ordering = MediaStore.Images.Media.DEFAULT_SORT_ORDER;
			switch (this.sortOrder) {
				case 1:
					ordering = MediaColumns.TITLE;
					break;
				case 2:
					ordering = ImageColumns.DATE_TAKEN;
					break;
				default:
					ordering = MediaStore.Images.Media.DEFAULT_SORT_ORDER;
					break;
			}
			String orient = "DESC";
			if (this.sortOrient) {
				orient = "ASC";
			}
			CursorLoader cLoaderExt = new CursorLoader(this, uriExt, projection, selection, new String[] { path + JOKER_STRING }, String.format("UPPER(%s) %s", ordering, orient));
			cLoaderExt.registerListener(0, this);
			CursorLoader cLoaderInt = new CursorLoader(this, uriInt, projection, selection, new String[] { path + JOKER_STRING }, ordering);
			cLoaderInt.registerListener(0, this);
			cLoaderExt.startLoading();
			cLoaderInt.startLoading();
		} else {
			SystemHelper.msjShortToast(R.string.err_no_path);
		}
	}

	/**
	 * @param bundle
	 * 
	 */
	private void setupPager(Bundle bundle) {
		AQuery aq = new AQuery(this);
		if (this.mLista != null) {
			this.pagerAdapter = new WebViewPagerAdapter(this.getSupportFragmentManager(), this.mLista);
			this.viewPager = (ViewPager) aq.id(R.id.gallerySwipePager).getView();
			this.viewPager.setAdapter(this.pagerAdapter);
			this.viewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
				@Override
				public void onPageSelected(int position) {
					Log.d(SystemHelper.APP_TAG, " Page selected " + position);

					FullscreenArrayFragment f = (FullscreenArrayFragment) PresentationActivity.this.pagerAdapter.getItem(position);

					Bundle bolsillo = f.getArguments();

					PresentationActivity.this.getSupportActionBar().setTitle(bolsillo.getString(FullscreenArrayFragment.BUNDLE_TITLE));
					PresentationActivity.this.setupShare(PresentationActivity.this.getFotoById(bolsillo.getLong(FullscreenArrayFragment.BUNDLE_ID)));
				}

				@Override
				public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

				}

				@Override
				public void onPageScrollStateChanged(int state) {

				}
			});
			long imgID = bundle.getLong(PARAM_PHOTO_ID, -1);
			if (imgID > 0) {
				this.viewPager.setCurrentItem(this.mLista.indexOf(this.getFotoById(imgID)), false);
				this.getSupportActionBar().setTitle(this.getFotoById(imgID).getTitulo());
				this.setupShare(this.getFotoById(imgID));
			}
		}
	}

	protected Foto getFotoById(long imgID) {
		Foto res = null;
		if ((this.mLista != null) && !this.mLista.isEmpty()) {
			for (Foto iFoto : this.mLista) {
				if ((iFoto != null) && (iFoto.getImgID() == imgID)) {
					res = iFoto;
					break;
				}
			}
		}
		return res;
	}

	private void setupShare(Foto foto) {
		if (foto != null) {
			this.mShareIntent = new Intent();
			this.mShareIntent.setAction(Intent.ACTION_SEND);
			this.mShareIntent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(new File(foto.getPath())));
			if (foto.getTitulo() != null) {
				this.mShareIntent.putExtra(Intent.EXTRA_TITLE, "Rembrandt: " + foto.getTitulo());
				this.mShareIntent.putExtra(Intent.EXTRA_SUBJECT, "Rembrandt Gallery: Shared Image [" + foto.getTitulo() + "]");
			}
			if (foto.getFecha() != null) {
				Date fecha = foto.getFecha();
				this.mShareIntent.putExtra(Intent.EXTRA_TEXT, "Rembrandt Galllery: Shared Image \n NAME " + foto.getTitulo() + "\n DATE " + DateFormat.getDateInstance().format(fecha));
			}
			this.mShareIntent.setType("image/*");
		}
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
			case android.R.id.home:
				this.finish();
				return true;
			case R.id.mnu_itm_share:
				this.mShareIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET);
				this.startActivity(Intent.createChooser(this.mShareIntent, SystemHelper.getLocalizedString(R.string.ab_itm_share)));
				return true;
		}
		return super.onOptionsItemSelected(item);
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate menu resource file.
		this.getSupportMenuInflater().inflate(R.menu.menu_presentation, menu);

		// Return true to display menu
		return true;
	}

	@Override
	public void onLoadComplete(Loader<Cursor> cLoader, Cursor cursor) {
		if ((cursor != null) && (cursor.getCount() > 0)) {
			cursor.moveToFirst();
			while (!cursor.isAfterLast()) {
				int col_idx_id = cursor.getColumnIndexOrThrow(BaseColumns._ID);
				int col_idx_data = cursor.getColumnIndexOrThrow(MediaColumns.DATA);
				int col_idx_date_taken = cursor.getColumnIndexOrThrow(ImageColumns.DATE_TAKEN);
				int col_idx_date_added = cursor.getColumnIndexOrThrow(MediaColumns.DATE_ADDED);
				int col_idx_title = cursor.getColumnIndexOrThrow(MediaColumns.TITLE);
				int col_idx_display = cursor.getColumnIndexOrThrow(MediaColumns.DISPLAY_NAME);
				int col_idx_desc = cursor.getColumnIndexOrThrow(ImageColumns.DESCRIPTION);

				long fechaLong = -1;
				Date fecha = null;
				String titolo = null;

				// ** RESUELVO DATE **
				try {
					fechaLong = cursor.getLong(col_idx_date_taken);
					Log.d(SystemHelper.APP_TAG, "Using Date Taken for pic ID: " + cursor.getLong(col_idx_id));
				} catch (Exception e) {
					Log.d(SystemHelper.APP_TAG, "No Date Taken for pic ID: " + cursor.getLong(col_idx_id));
				}
				if (fechaLong < 0) {
					try {
						fechaLong = cursor.getLong(col_idx_date_added);
						Log.d(SystemHelper.APP_TAG, "Using Date Added for pic ID: " + cursor.getLong(col_idx_id));
					} catch (Exception e) {
						Log.d(SystemHelper.APP_TAG, "No Date Added for pic ID: " + cursor.getLong(col_idx_id));
					}
				}
				if (fechaLong > 0) {
					fecha = new Date(fechaLong);
				}

				// ** RESUELVO TITULO **
				try {
					titolo = cursor.getString(col_idx_title);
					Log.d(SystemHelper.APP_TAG, "Using Title for pic ID: " + cursor.getLong(col_idx_id));
				} catch (Exception e) {
					Log.d(SystemHelper.APP_TAG, "No Title for pic ID: " + cursor.getLong(col_idx_id));
				}
				if ((titolo == null) || titolo.trim().equals(EMPTY_STRING)) {
					try {
						titolo = cursor.getString(col_idx_display);
						Log.d(SystemHelper.APP_TAG, "Using Display Name for pic ID: " + cursor.getLong(col_idx_id));
					} catch (Exception e) {
						Log.d(SystemHelper.APP_TAG, "No Display Name for pic ID: " + cursor.getLong(col_idx_id));
					}
				}
				if ((titolo == null) || titolo.trim().equals(EMPTY_STRING)) {
					try {
						titolo = cursor.getString(col_idx_desc);
						Log.d(SystemHelper.APP_TAG, "Using Description for pic ID: " + cursor.getLong(col_idx_id));
					} catch (Exception e) {
						Log.d(SystemHelper.APP_TAG, "No Description Name for pic ID: " + cursor.getLong(col_idx_id));
					}
				}

				this.agregarThumbnailALista(cursor.getLong(col_idx_id), cursor.getString(col_idx_data), fecha, titolo);
				cursor.moveToNext();
			}
			this.setupPager(this.getIntent().getExtras());
		}
	}

	private void agregarThumbnailALista(long imgID, String path, Date fecha, String titolo) {
		if (this.mLista == null) {
			this.mLista = new ArrayList<Foto>();
		}
		this.mLista.add(new Foto(imgID, path, titolo, fecha));
	}
}
